﻿using Simple.Http;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace Simple.Tools.http
/// <summary>
/// 版 本 钢易智企2.0 V 2.0.0 钢易智企2.0
/// Copyright (c) 2023 杭州钢易科技有限公司
/// 创建人：曾东明
/// 日 期：2024
/// 描 述：
/// </summary>
{
	/// <summary>
	/// 
	/// </summary>
	public class HttpContextClient
	{
		/// <summary>
		/// 
		/// </summary>
		private HttpClient _httpClient;

		/// <summary>
		/// 
		/// </summary>
		private static Dictionary<string, object> _headers;
		/// <summary>
		/// 
		/// </summary>
		private static Action<HttpResponseMessage,Exception> _errorHandler;
		/// <summary>
		/// 
		/// </summary>
		public HttpContextClient(string baseUrl)
		{
			if (SimpleCheck.IsNullOrEmpty(baseUrl))
			{
				throw new ArgumentNullException("base url is null or empty!");
			}
			_httpClient = new HttpClient();
			_httpClient.BaseAddress = new Uri(baseUrl);
			_headers = new Dictionary<string, object>();
		}
		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public HttpClient GetHttpClient()
		{
			return _httpClient;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public Dictionary<string, object> GetHeaders()
		{
			return _headers;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		public  void AddHead(string key, object value)
		{
			if (_headers.ContainsKey(key))
			{
				_headers.Remove(key);
			}
			_headers.Add(key, value);
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="key"></param>
		public  void RemoveHead(string key)
		{
			if (_headers.ContainsKey(key))
			{
				_headers.Remove(key);
			}
		}
		/// <summary>
		/// 
		/// </summary>
		public  void ClearHead()
		{
			_headers.Clear();
		}


		/// <summary>
		/// 
		/// </summary>
		/// <param name="errorHandler"></param>
		public  void SetError(Action<HttpResponseMessage,Exception> errorHandler)
		{
			_errorHandler = errorHandler;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="response"></param>
		/// <param name="ex"></param>
		public void ErrorInvoke(HttpResponseMessage response,Exception ex)
		{
			if (SimpleCheck.IsNull(_errorHandler))
			{
				return;
			}
			_errorHandler(response,ex);
		}

	}
}
